package com.yupi.yupicturebackend.manager.upload;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.yupi.yupicturebackend.config.CosClientConfig;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.manager.CosManager;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;


@Slf4j
public abstract class PictureUploadTemplate {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 上传图片
     */
    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 校验图片
        validPicture(inputSource);
        // 图片上传地址
        String uuid = RandomUtil.randomString(8);
        // 文件名
        String orginalFilename = getOrginalFilename(inputSource);
        String fileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, orginalFilename);
        String filepath = String.format("/%s/%s", uploadPathPrefix, fileName);
        File file = null;
        try {
            // 创建临时文件
            file  = File.createTempFile(filepath, null);
            //处理文件来源
            processFile(inputSource, file);
            // 上传文件
            PutObjectResult putObjectResult = cosManager.putPictureObject(filepath, file);
            // 解析结果
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if(CollUtil.isNotEmpty(objectList)){
                // 压缩图片的结果
                CIObject compressedCiObject = objectList.get(0);
                // 缩略图结果
                CIObject thumbnailCiObject = compressedCiObject;
                if (objectList.size() > 1){
                    thumbnailCiObject = objectList.get(1);
                }
                return buildResult(fileName,compressedCiObject, thumbnailCiObject, imageInfo);
            }
            // 返回结果
            return buildResult(filepath, fileName, file, imageInfo);
        } catch (Exception e) {
            log.info("图片上传失败" ,e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        }finally {
            deleteTempFile(file);
            }
        }




    /**
     * 处理文件来源
     */
    protected abstract void processFile(Object inputSource,File file) throws Exception;

    /**
     * 获取原始文件名
     */
    protected abstract String getOrginalFilename(Object inputSource);

    /**
     * 校验图片
     */
    protected abstract void validPicture(Object inputSource);


    /**
     * 构建结果
     */
    private UploadPictureResult buildResult(String fileName, CIObject compressedCiObject, CIObject thumbnailCiObject,ImageInfo imageInfo) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        // 压缩图片地址
        uploadPictureResult.setUrl(cosClientConfig.getHost() +"/"+ compressedCiObject.getKey());
        uploadPictureResult.setPicName(fileName);
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        uploadPictureResult.setPicWidth(compressedCiObject.getWidth());
        uploadPictureResult.setPicHeight(compressedCiObject.getHeight());
        double scale = (double) compressedCiObject.getWidth() / (double) compressedCiObject.getHeight();
        uploadPictureResult.setPicScale(scale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        uploadPictureResult.setPicColor(imageInfo.getAve());
        // 缩略图地址
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() +"/"+ thumbnailCiObject.getKey());
        return uploadPictureResult;
    }
    /**
     * 构建结果
     */
    private UploadPictureResult buildResult(String fileName, CIObject compressedCiObject) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosClientConfig.getHost() +"/"+ compressedCiObject.getKey());
        uploadPictureResult.setPicName(fileName);
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        uploadPictureResult.setPicWidth(compressedCiObject.getWidth());
        uploadPictureResult.setPicHeight(compressedCiObject.getHeight());
        double scale = (double) compressedCiObject.getWidth() / (double) compressedCiObject.getHeight();
        uploadPictureResult.setPicScale(scale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        return uploadPictureResult;
    }
        /**
         * 构建结果
         */
    private UploadPictureResult buildResult(String filepath, String fileName, File file, ImageInfo imageInfo) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosClientConfig.getHost() +"/"+ filepath);
        uploadPictureResult.setPicName(fileName);
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicWidth(imageInfo.getWidth());
        uploadPictureResult.setPicHeight(imageInfo.getHeight());
        double scale = (double) imageInfo.getWidth() / (double) imageInfo.getHeight();
        uploadPictureResult.setPicScale(scale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        uploadPictureResult.setPicColor(imageInfo.getAve());
        return uploadPictureResult;
    }


    /**
     * 删除临时文件
     */
    private void deleteTempFile(File file) {
        if (file != null) {
            // 删除临时文件
            boolean delete = file.delete();
            if (!delete) {
                log.error("file delete error, filepath =" + file.getAbsolutePath());
            }
        }
    }



}




